package com.geekchique.runningbuddy.activity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Spinner;

import com.geekchique.runningbuddy.R;
import com.geekchique.runningbuddy.controller.IMapOfJogController;
import com.geekchique.runningbuddy.controller.MapOfJogControllerImpl;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.googlenav.DrivingDirection;
import com.google.googlenav.map.MapPoint;

public class MapOfJog extends MapActivity {
	
	private IMapOfJogController mapOfJogController;

	private String[][] locations = 
	{ 
		  { "Tullis", "-4.229920, 55.846809" },
          { "Glasgow Green", "-4.232676,55.846904" }
	};

	public DrivingDirection myDD = null;
	public boolean foundDirections = false;

	private DrivingDirection drivingDirections;
          
  @Override
  public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      this.setContentView(R.layout.mapview);
      
      mapOfJogController = new MapOfJogControllerImpl(this);
		
		
      mapOfJogController.createMapOfJogView(
    		  (Button)findViewById(R.id.go),
    		  (Spinner)findViewById(R.id.spinner1),
    		  android.R.layout.simple_spinner_dropdown_item,
    		  (MapView)findViewById(R.id.map),
    		  locations);
		
  	}
	/** Offers the DrivingDirections to the Overlay. */
	public DrivingDirection getDrivingDirections() {
		return this.drivingDirections;
	}

	public void updateOnScreenDirections(MapPoint from_pos, String from_name, MapPoint to_pos, String to_name) {
		this.drivingDirections = new DrivingDirection(from_pos, from_name, to_pos, to_name);

		if (this.drivingDirections != null) {
			this.getDispatcher().addDataRequest(this.drivingDirections);

			Thread requestDrivingDirections = requestForDirectionsThread();
			requestDrivingDirections.start();
		}
	}

	private Thread requestForDirectionsThread() {
		Thread directionsRequest = new Thread(new Runnable() {
			public void run() {
				
				while (directionsRequestIsIncomplete()) { 
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						Log.e("TAG", "Map directions Interuppted",e);
					}
				}
				
				if (directionsSuccessfullyRetrieved()) {
					MapOfJog.this.foundDirections = true;
				} else { 
					MapOfJog.this.foundDirections = true;
					MapOfJog.this.drivingDirections = null;
				}
			}
			
			public boolean directionsRequestIsIncomplete(){
				return !MapOfJog.this.drivingDirections.isComplete();
			}
			
			public boolean directionsSuccessfullyRetrieved(){
				return MapOfJog.this.drivingDirections.getState() != DrivingDirection.SUCCESS_STATUS;
			}
			
		});
		
		return directionsRequest;
	}
  
}